import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction import DictVectorizer
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier


# 1.读取数据
path = "../src/titanic/titanic.csv"
data = pd.read_csv(path)
x = data[["pclass", "age", "sex"]]                 # 筛选特征值
x["age"] = x["age"].fillna(x["age"].mean())        # 处理缺失值
y = data["survived"]                               # 筛选目标值
x = x.to_dict(orient="records")                    # 转换为字典

# 2. 数据集划分
x_train,  x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=22)

# 3. 特征工程：特征提取
transfer = DictVectorizer(sparse=False)    # 返回ndarray，而不是稀疏矩阵
x_train = transfer.fit_transform(x_train)
x_test = transfer.transform(x_test)

# 4. 特征工程：标准化
scaler = StandardScaler()
x_train = scaler.fit_transform(x_train)
x_test = scaler.transform(x_test)

# 5. 模型训练：随机森林预估器
estimator = RandomForestClassifier(random_state=22)
estimator.fit(x_train, y_train)

# 6. 模型评估
# 法1：直接对比真实值和预测值
y_predict = estimator.predict(x_test)
print("预测值：\n", y_predict)
print("真实值和预测值比对：\n", y_test == y_predict)
# 法2：计算准确率
score = estimator.score(x_test, y_test)
print("准确率为：\n", score)
